package org.example.StudentManagementSystem.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.example.StudentManagementSystem.entity.Grade;
import org.example.StudentManagementSystem.common.Result;
import org.example.StudentManagementSystem.dto.request.GradeDTO;
import org.example.StudentManagementSystem.service.CourseService;
import org.example.StudentManagementSystem.service.GradeService;
import org.example.StudentManagementSystem.service.StudentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Tag(name = "Grade Controller", description = "成绩管理相关API")
@RestController
@RequestMapping("/grade")
@CrossOrigin(origins = "*")
public class GradeController {
    @Autowired
    private GradeService gradeService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private CourseService courseService;

    /**
     * 将Grade 转换为 GradeDTO
     */
    public GradeDTO convertToDTO(Grade grade) {
        GradeDTO gradeDTO = new GradeDTO();
        BeanUtils.copyProperties(grade, gradeDTO);
        if (grade.getStudentId() != null) {
            gradeDTO.setStudentName(studentService.getById(grade.getStudentId()).getName());
        }
        if (grade.getCourseId() != null) {
            gradeDTO.setCourseName(courseService.getById(grade.getCourseId()).getName());
        }
        return gradeDTO;
    }

    /**
     * 获取成绩列表
     */
    @Operation(summary = "获取成绩列表", description = "分页获取成绩列表")
    @ApiResponse(responseCode = "200", description = "获取成功", content = @Content(schema = @Schema(implementation = Result.class)))
    @GetMapping("")
    public Result getGradeList(
            @Parameter(description = "页码", required = true) @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页大小", required = true) @RequestParam(defaultValue = "10") int size) {
        Page<Grade> gradePage = gradeService.page(Page.of(page, size));
        if (gradePage.getTotal() == 0) {
            return Result.error("暂无数据");
        }
        List<GradeDTO> gradeDTOList = gradePage.getRecords().stream().map(this::convertToDTO).collect(Collectors.toList());
        Page<GradeDTO> gradeDTOPage = new Page<>();
        gradeDTOPage.setCurrent(gradePage.getCurrent());
        gradeDTOPage.setSize(gradePage.getSize());
        gradeDTOPage.setTotal(gradePage.getTotal());
        gradeDTOPage.setRecords(gradeDTOList);
        return Result.success(gradeDTOPage, "获取成绩列表成功");
    }

    /**
     * 获取所有成绩
     */
    @Operation(summary = "获取所有成绩", description = "获取所有成绩")
    @ApiResponse(responseCode = "200", description = "获取成功", content = @Content(schema = @Schema(implementation = Result.class)))
    @GetMapping("/all")
    public Result getAllGrade() {
        List<Grade> gradeList = gradeService.list();
        if (gradeList.isEmpty()) {
            return Result.error("暂无数据");
        }
        List<GradeDTO> gradeDTOList = gradeList.stream().map(this::convertToDTO).collect(Collectors.toList());
        return Result.success(gradeDTOList, "获取所有成绩成功");
    }

    /**
     * 根据id获取成绩
     */
    @Operation(summary = "根据ID获取成绩", description = "根据ID获取成绩")
    @ApiResponse(responseCode = "200", description = "获取成功", content = @Content(schema = @Schema(implementation = Result.class)))
    @ApiResponse(responseCode = "404", description = "成绩不存在", content = @Content(schema = @Schema(implementation = Result.class)))
    @GetMapping("/{id}")
    public Result getGradeById(@PathVariable @Parameter(description = "成绩ID", required = true) int id) {
        Grade grade = gradeService.getById(id);
        if (grade == null) {
            return Result.error("成绩不存在");
        }
        GradeDTO gradeDTO = convertToDTO(grade);
        return Result.success(gradeDTO, "获取成绩成功");
    }

    /**
     * 新增成绩
     */
    @Operation(summary = "新增成绩", description = "新增成绩")
    @ApiResponse(responseCode = "200", description = "添加成功", content = @Content(schema = @Schema(implementation = Result.class)))
    @ApiResponse(responseCode = "400", description = "信息不完整", content = @Content(schema = @Schema(implementation = Result.class)))
    @PostMapping("")
    public Result addGrade(@RequestBody @Parameter(description = "成绩信息", required = true) Grade grade) {
        if (grade.getStudentId() == null || grade.getCourseId() == null || grade.getGrade() == null) {
            return Result.error("成绩信息不完整");
        }
        return gradeService.save(grade) ? Result.success(grade, "成绩添加成功") : Result.error("成绩添加失败");
    }

    /**
     * 修改成绩
     */
    @Operation(summary = "修改成绩", description = "根据ID修改成绩")
    @ApiResponse(responseCode = "200", description = "修改成功", content = @Content(schema = @Schema(implementation = Result.class)))
    @ApiResponse(responseCode = "400", description = "信息不完整", content = @Content(schema = @Schema(implementation = Result.class)))
    @ApiResponse(responseCode = "404", description = "成绩不存在", content = @Content(schema = @Schema(implementation = Result.class)))
    @PutMapping("/{id}")
    public Result updateGrade(@PathVariable @Parameter(description = "成绩ID", required = true) int id,
                              @RequestBody @Parameter(description = "新的成绩信息", required = true) Grade grade) {
        if (grade.getStudentId() == null || grade.getCourseId() == null || grade.getGrade() == null) {
            return Result.error("成绩信息不完整");
        }
        grade.setId(id);
        return gradeService.updateById(grade) ? Result.success(grade, "成绩修改成功") : Result.error("成绩修改失败");
    }

    /**
     * 删除成绩
     */
    @Operation(summary = "删除成绩", description = "根据ID删除成绩")
    @ApiResponse(responseCode = "200", description = "删除成功", content = @Content(schema = @Schema(implementation = Result.class)))
    @ApiResponse(responseCode = "404", description = "成绩不存在", content = @Content(schema = @Schema(implementation = Result.class)))
    @DeleteMapping("/{id}")
    public Result deleteGrade(@PathVariable @Parameter(description = "成绩ID", required = true) int id) {
        if (gradeService.getById(id) == null) {
            return Result.error("成绩不存在");
        }
        return gradeService.removeById(id) ? Result.success(null, "成绩删除成功") : Result.error("成绩删除失败");
    }

    /**
     * 批量删除成绩
     */
    @Operation(summary = "批量删除成绩", description = "根据ID列表批量删除成绩")
    @ApiResponse(responseCode = "200", description = "批量删除成功", content = @Content(schema = @Schema(implementation = Result.class)))
    @ApiResponse(responseCode = "400", description = "未选择记录", content = @Content(schema = @Schema(implementation = Result.class)))
    @ApiResponse(responseCode = "404", description = "成绩不存在", content = @Content(schema = @Schema(implementation = Result.class)))
    @DeleteMapping("")
    public Result deleteGrades(@RequestBody @Parameter(description = "成绩ID列表", required = true) int[] ids) {
        if (ids.length == 0) {
            return Result.error("请选择要删除的记录");
        }
        for (int id : ids) {
            if (gradeService.getById(id) == null) {
                return Result.error("成绩不存在");
            }
        }
        List<Integer> idList = Arrays.stream(ids).boxed().collect(Collectors.toList());
        return gradeService.removeBatchByIds(idList) ? Result.success("批量删除成绩成功") : Result.error("批量删除成绩失败");
    }

}
